<?php

/**
 * @author TEAM03-HEDSPI
 * @copyright 2012
 * @description 会議室を操作するためクラス
 */
include_once('ConnectionDatabase.php');
class Room{
    private $connect;
    
    /**
     * @author Hiendv
     * @description 構造メソッド
    */
    public function __construct(){
        $this->connect = new ConnectionDatabase();
    }
    
    /**
     * @author HIENDV
     * @description 会議室IDによって会議室の情報を引き出すためメソッド
	 * @param unknown_type $room_id
     * @return Thong tin phong theo room_id
	 */
	function get_room_info_by_id($room_id){
	    $mysqli = $this->connect->getMysqli();
	    $db_name = $this->connect->getDB_name();
	    $sql="select a.* from $db_name.room a where a.room_id=$room_id";
	   // echo $sql;
	    $result=$mysqli->query($sql);
	    $row='';
	    if ($stmt = $mysqli->prepare($sql)) {
	        $stmt->execute();
	        /* bind variables to prepared statement */
	        $stmt->bind_result($row['room_id'],$row['room_name'],$row['chair'],$row['price'],
	                            $row['description'],$row['avatar']);
	        /* fetch values */
	        while ($stmt->fetch()) {
	        }
	        /* close statement */
	        $stmt->close();
	    }
	    return $row;
	}
    /**
     * @author HIENDV
     * @description 会議室IDによって会議室の情報を引き出すためメソッド
	 * @param unknown_type $room_id
     * @return Thong tin phong theo room
	 */
     function get_list_room_for_user($type_room,$date,$start_time,$end_time,$type,$page,$per_page){
        $mysqli = $this->connect->getMysqli();
		$db_name = $this->connect->getDB_name();
		if($type==1){
			$sql = " SELECT a.* FROM $db_name.room a";
		}else if($type==2){
            $sql = " SELECT count(*) FROM $db_name.room a";
		}
        $start_time=$date.' '.$start_time;
        $end_time=$date.' '.$end_time;
		$oder_by = " order by a.room_id ";
		$where = " where 1=1 ";
		if($date != ''){
			$where = $where." and a.room_id not in (
            SELECT distinct a.room_id FROM $db_name.room a,$db_name.order b
            where a.room_id=b.room_id and upper(b.start_time) like upper('%".$date."%') and ((b.start_time >='$start_time' and b.start_time<= '$end_time') or 
            (b.end_time>= '$start_time' and b.end_time <='$end_time')))";
		}
		//echo 'roomname='.$room_name;
		if($type_room== '1'){
			$where = $where." and a.chair>=6";
		}
 	    else if($type_room== '2'){
			$where = $where." and a.chair<6";
		}
		//echo $where;
		$sql=$sql.$where.$oder_by;
        //echo $sql;
		if($type==1){
            $sql=$sql.' limit '.($page*$per_page-$per_page).','.$per_page;
            $result = $mysqli->query($sql);
            $i=0;
            $rs=''; 
    	 	while($row = $result->fetch_array(MYSQLI_ASSOC))
    	 	{
                 $rs[$i][0]= $row['room_id'];
                 $rs[$i][1]= $row['room_name'];
                 $rs[$i][2]= $row['chair'];
                 $rs[$i][3]= $row['price'];
                 $rs[$i][4]= $row['description'];
            	 $rs[$i][5]= $row['avatar'];
                 $i=$i+1;
    	 	}
            $result->close();
    	 	return $rs;
       }else if($type==2){
            $totalPage=0;
			//echo $sql;
            if ($stmt = $mysqli->prepare($sql)) {
                $stmt->execute();
            /* bind variables to prepared statement */
                $stmt->bind_result($totalPage);
            /* fetch values */
            while ($stmt->fetch()) {
            }
            /* close statement */
            $stmt->close();
            }
           // echo $totalPage;
            return $totalPage;
       } 	 
     }
     function get_list_page_for_user($type_room,$date,$start_time,$end_time,$page,$per_page){
        $totalrecord = $this->get_list_room_for_user($type_room,$date,$start_time,$end_time,2,$page,$per_page);
        if($totalrecord<=$per_page){
            $result[0]=1;
        }
        else{
            for($i=0;$i<($totalrecord/$per_page);$i++){
                $rs[$i]=$i+1;
            }
            //echo count($rs);
            if(count($rs)>5){
                if($page<=4){
                    for($i=0;$i<5;$i++){
                        $result[$i]=$i+1;
                    $result[5]=-2;    
                    }
                }
                else if($page>4 && $page<(count($rs)-3)){
                    //echo 'day nay';
                    $result[0]=-1;
                    $result[6]=-2;
                    for($i=1;$i<6;$i++){
                         $result[$i]=$rs[$page-3+$i];    
                    }
                }
                else {
                    $result[0]=-1;
                    for($i=5;$i>0;$i--){
                        $result[$i]=$rs[(count($rs)+$i-6)];
                    }
                }                
            }
            else{$result=$rs;}
        }
        return $result;
     }
     
     /**
     * @author HIENDV
     * @description 会議室IDによって会議室の情報を引き出すためメソッド
	 * @param unknown_type $room_id
     * @return Thong tin phong theo room
	 */
     function get_list_room_for_user_1($room_name,$typeRoom,$type,$page,$per_page){
        $mysqli = $this->connect->getMysqli();
		$db_name = $this->connect->getDB_name();
		if($type==1){
			$sql = " SELECT a.* FROM $db_name.room a";
		}else if($type==2){
            $sql = " SELECT count(*) FROM $db_name.room a";
		}
		$oder_by = " order by a.room_id ";
		$where = " where 1=1 ";
		//echo 'roomname='.$room_name;
		if($room_name != ''){
			$where = $where." and upper(a.room_name) like upper('%".$room_name."%')";
		}
        if($typeRoom == '1'){
			$where = $where." and a.chair >=6 ";
		}
        else if($typeRoom == '2'){
			$where = $where." and a.chair<6";
		}
		//echo $where;
		$sql=$sql.$where.$oder_by;
        //echo $sql;
		if($type==1){
            $sql=$sql.' limit '.($page*$per_page-$per_page).','.$per_page;
            //echo $sql;
            $result = $mysqli->query($sql);
            $i=0;
            $rs=''; 
    	 	while($row = $result->fetch_array(MYSQLI_ASSOC))
    	 	{
                 $rs[$i][0]= $row['room_id'];
                 $rs[$i][1]= $row['room_name'];
                 $rs[$i][2]= $row['chair'];
                 $rs[$i][3]= $row['price'];
                 $rs[$i][4]= $row['description'];
            	 $rs[$i][5]= $row['avatar'];
                 $i=$i+1;
    	 	}
            $result->close();
    	 	return $rs;
       }else if($type==2){
            $totalPage=0;
			//echo $sql;
            if ($stmt = $mysqli->prepare($sql)) {
                $stmt->execute();
            /* bind variables to prepared statement */
                $stmt->bind_result($totalPage);
            /* fetch values */
            while ($stmt->fetch()) {
            }
            /* close statement */
            $stmt->close();
            }
           // echo $totalPage;
            return $totalPage;
       } 	 
     }
     function get_list_page_for_user_1($room_name,$typeRoom,$page,$per_page){
        $totalrecord = $this->get_list_room_for_user_1($room_name,$typeRoom,2,$page,$per_page);
        if($totalrecord<=$per_page){
            $result[0]=1;
        }
        else{
            for($i=0;$i<($totalrecord/$per_page);$i++){
                $rs[$i]=$i+1;
            }
            //echo count($rs);
            if(count($rs)>5){
                if($page<=4){
                    for($i=0;$i<5;$i++){
                        $result[$i]=$i+1;
                    $result[5]=-2;    
                    }
                }
                else if($page>4 && $page<(count($rs)-3)){
                    //echo 'day nay';
                    $result[0]=-1;
                    $result[6]=-2;
                    for($i=1;$i<6;$i++){
                         $result[$i]=$rs[$page-3+$i];    
                    }
                }
                else {
                    $result[0]=-1;
                    for($i=5;$i>0;$i--){
                        $result[$i]=$rs[(count($rs)+$i-6)];
                    }
                }                
            }
            else{$result=$rs;}
        }
        return $result;
     }
    
    /**
     * @author HIENDV
	 * @description すべての会議室リストを引き出す
	 * @param  $room_id
     * @param $room_name
     * @param $type
     * @param $page
     * @param $per_page
     * @return 会議室リスト
	 */
	function get_list_room($room_id,$room_name,$type,$page,$per_page){
        $mysqli = $this->connect->getMysqli();
		$db_name = $this->connect->getDB_name();
		if($type==1){
			$sql = " SELECT a.* FROM $db_name.room a ";
		}else if($type==2){
			$sql= " SELECT count(*) FROM $db_name.room a ";
		}
		$oder_by = " order by a.room_id ";
		$where = " where 1=1 ";
		if($room_id != ''){
			$where = $where." and a.room_id=$room_id";
		}
		//echo 'roomname='.$room_name;
		if($room_name != ''){
			$where = $where." and upper(a.room_name) like upper('%".$room_name."%')";
		}
		//echo $where;
		$sql=$sql.$where.$oder_by;
        //echo $sql;
		if($type==1){
            $sql=$sql.' limit '.($page*$per_page-$per_page).','.$per_page;
            //echo $sql;
            $result = $mysqli->query($sql);
            $i=0;
            $rs=''; 
    	 	while($row = $result->fetch_array(MYSQLI_ASSOC))
    	 	{
                 $rs[$i][0]= $row['room_id'];
                 $rs[$i][1]= $row['room_name'];
                 $rs[$i][2]= $row['chair'];
                 $rs[$i][3]= $row['price'];
                 $rs[$i][4]= $row['description'];
            	 $rs[$i][5]= $row['avatar'];
                 $i=$i+1;
    	 	}
            $result->close();
    	 	return $rs;
       }else if($type==2){
            $totalPage=0;
			//echo $sql;
            if ($stmt = $mysqli->prepare($sql)) {
                $stmt->execute();
            /* bind variables to prepared statement */
                $stmt->bind_result($totalPage);
            /* fetch values */
            while ($stmt->fetch()) {
            }
            /* close statement */
            $stmt->close();
            }
           // echo $totalPage;
            return $totalPage;
       } 	 
    }
   
   
   /**
     * @author Hiendv
	 * @description 新しい会議室を追加するためメソッド
	 * @param $room_id not null
     * @param $room_name not null
     * @param $chair not null
     * @param $price not null
     * @param $description 
     * @param $avatar
     * @return 0 また 1
	 */
	function insert_room($room_name,$chair,$price,$description,$avatar){
     	$mysqli = $this->connect->getMysqli();
		$db_name = $this->connect->getDB_name();
        $sql="insert into $db_name.room values(null,'".$room_name."','".$chair."','".$price."','".$description."','".$avatar."')";
        //echo $sql;
        $mysqli->query("BEGIN");
        $rs=$mysqli->query($sql);
		if($rs){
			// Ghi vao file Log
			// Code de day
				
			
            $mysqli->query("COMMIT");
			$result=1;
		}
		else $result=0;
        $mysqli->close();
        return $result; 
	}
    
    
	/**
	 * @author Hiendv
     * @description 一つの会議室の情報を編成すえるためメソッド
	 * @param unknown_type $room_name
	 * @param unknown_type $chair
	 * @param unknown_type $price
	 * @param unknown_type $description
	 * @param unknown_type $avatar
	 * @param unknown_type $room_id
     * @return 0また１
	 */
	function edit_room($room_name,$chair,$price,$description,$avatar,$room_id){
        $mysqli = $this->connect->getMysqli();
		$db_name = $this->connect->getDB_name();
        $sql="update $db_name.room set room_name='".$room_name."',chair='".$chair."',price='".$price."',description='".$description."',avatar='".$avatar."' 
                where room_id=$room_id";
        //echo $sql;
        $mysqli->query("BEGIN");
        $rs=$mysqli->query($sql);
		if($rs){
			// Ghi vao file Log
			// Code de day			
            $mysqli->query("COMMIT");
			$result=1;
		}
		else $result=0;
        $mysqli->close();
        return $result; 
}


    /**
     * @author Hiendv
	 * @description 一つの会議室を削除するためメソッド
	 * @param $room_id not null
	 * @return TRUE また FLASE
     */
	function delete_room($id){
	    $mysqli = $this->connect->getMysqli();
		$db_name = $this->connect->getDB_name();
        $sql="select count(*) from $db_name.order a where a.room_id=$id and a.status!=2";
        $row=0;
        if ($stmt = $mysqli->prepare($sql)) {
                $stmt->execute();
            /* bind variables to prepared statement */
                $stmt->bind_result($row);
            /* fetch values */
            while ($stmt->fetch()) {
            }
            /* close statement */
            $stmt->close();
            }
        if($row == 0){
            $sql="delete a.* from $db_name.room a where a.room_id=$id";
            //echo $sql;
            $mysqli->query("BEGIN");
            $rs=$mysqli->query($sql);
    		if($rs){
    			// Ghi vao file Log
    			// Code de day			
                $mysqli->query("COMMIT");
    			return 'TRUE';
    		}
            else return 'FALSE';
        }
        else{
            return 'FALSE';   
        }
       
	}
    
    
	 /**
     * @author Hiendv
	 * @description ページを分けるためメソッド
	 * @param unknown_type $room_id not null
     * @param unknown_type $room_name not null
     * @param unknown_type $page
     * @param unknown_type $per_page
     * @return 会議室リスト
	 */
	
	function listpage($room_id,$room_name,$page,$per_page){
        $totalrecord = $this->get_list_room($room_id,$room_name,2,$page,$per_page);
        if($totalrecord<=$per_page){
            $result[0]=1;
        }
        else{
            for($i=0;$i<($totalrecord/$per_page);$i++){
                $rs[$i]=$i+1;
            }
            //echo count($rs);
            if(count($rs)>5){
                if($page<=4){
                    for($i=0;$i<5;$i++){
                        $result[$i]=$i+1;
                    $result[5]=-2;    
                    }
                }
                else if($page>4 && $page<(count($rs)-3)){
                    //echo 'day nay';
                    $result[0]=-1;
                    $result[6]=-2;
                    for($i=1;$i<6;$i++){
                         $result[$i]=$rs[$page-3+$i];    
                    }
                }
                else {
                    $result[0]=-1;
                    for($i=5;$i>0;$i--){
                        $result[$i]=$rs[(count($rs)+$i-6)];
                    }
                }
                
            }
            else{$result=$rs;}
        }
        return $result;
    }
	
    
	/**
	 * @author Hienbv
	 * @description 会議室によって会議室情報を引き出すためメソッド
	 * @param unknown_type $room_id
	 * @return 会議室情報
     */
	function get_room_id($room_id) {
		$mysqli = $this->connect->getMysqli ();
		$db_name = $this->connect->getDB_name ();
		$sql = " SELECT a.* FROM $db_name.room a ";
		$where = " where 1=1 ";
		if ($room_id != '') {
			$where = $where . " and a.room_id=$room_id";
		}
		$sql = $sql . $where;
		
		$result = $mysqli->query ( $sql );
		$i = 0;
		$rs = '';
		while ( $row = $result->fetch_array ( MYSQLI_ASSOC ) ) {
			$rs [$i] [0] = $row ['room_id'];
			$rs [$i] [1] = $row ['room_name'];
			$rs [$i] [2] = $row ['chair'];
			$rs [$i] [3] = $row ['price'];
			$rs [$i] [4] = $row ['description'];
			$rs [$i] [5] = $row ['avatar'];
			break;
		}
		$result->close ();
		return $rs;           
	}
	
    
	 /**
     * @author Hienbv
	 * @description 新しい予約情報を追加するためメソッド
	 * @param unknown_type $room_id not null
     * @param unknown_type $user_id not null
     * @param unknown_type $price not null
     * @param unknown_type $timeStart not null
     * @param unknown_type $timeEnd 
	 * @return 成功の状態また失敗の状態
     */
function insert_put_room($room_id, $user_id, $price, $timeStart, $timeEnd) {
		try{
			//Check account co ton tai trong bang account k?
			if(!$this->check_exited_user_id($user_id)){
				return "このアカウントは存在していない。";
			}
			//Check thoi gian 
			$_start = substr($timeStart, 11);
			$_end = substr($timeEnd, 11);
			
			//$price = $price * ($this->convertTimeToNumber($_end)-$this->convertTimeToNumber($_start));
			
			$_date = substr($timeStart, 0, 9);
			if($this->check_date_put_room('', $room_id, $_date, $_start, $_end)){
				return "その会議室の時間は予約済みです。";
			}
			$mysqli = $this->connect->getMysqli ();
			$db_name = $this->connect->getDB_name ();
			$sql = "INSERT INTO $db_name.order (id, user_id, room_id, start_time, end_time, total, status, created_date) VALUES (null,'$user_id', $room_id, '$timeStart', '$timeEnd', $price, 1, now()) ";
			$mysqli->query($sql);
			$result=$mysqli->affected_rows;
	        $mysqli->close();
	        $file='../../../log/debug/'.date("Y-m-d").'.txt';
			$f=fopen($file,'a+');
			if($f){
				fwrite($f,"GET_INSERT_PUT_ROOM_SUCCESS: RoomID: ".$room_id." Username: ".$user_id." Price: ".$price." Start-time: ".$timeStart." End-time: ".$timeEnd." Date-debug:".gmdate('Y-m-d H:i:s')."\r");
			}
			fclose($f);
        	return "予約を受けた回りました。";
	                
		}catch(Exception $e){
	    	$file='../../../log/error/'.date("Y-m-d").'.txt';
			$f=fopen($file,'a+');
			if($f){
				fwrite($f,"GET_INSERT_PUT_ROOM_ERROR: RoomID: ".$room_id." Error: ".$e->getMessage()." Date-debug:".gmdate('Y-m-d H:i:s')."\r");
			}
			fclose($f);
			return "予想できないエラーは起こったので、もう一度お願いします。";  
	    }
	}
	
    
    /**
     * @author Hienbv
	 * @description 予約情報を編成するためメソッド
     * @param unknown_type $id not null
	 * @param unknown_type $room_id not null
     * @param unknown_type $status
     * @param unknown_type $price 
     * @param unknown_type $timeStart 
     * @param unknown_type $timeEnd 
     * @return 成功の状態また失敗の状態です。
	 */
function update_put_room($id, $room_id, $status, $price, $timeStart, $timeEnd, $timeExpired) {
		try{
			//Check account co ton tai trong bang account k?
			//Check thoi gian 
			$_start = substr($timeStart, 11);
			$_end = substr($timeEnd, 11);
			$_date = substr($timeStart, 0, 9);
			if($this->check_date_put_room($id, $room_id, $_date, $_start, $_end)){
				return "その会議室の時間は予約済みです。";
			}
			$mysqli = $this->connect->getMysqli ();
			$db_name = $this->connect->getDB_name ();
			$sql = "UPDATE $db_name.order SET room_id=$room_id ,start_time='".$timeStart."', end_time='".$timeEnd."', total='".$price."', status=$status, time_expired=$timeExpired WHERE id=$id";
			
			$mysqli->query($sql);
			$result=$mysqli->affected_rows;
	        $mysqli->close();
        	$file='../../../log/error/'.date("Y-m-d").'.txt';
			$f=fopen($file,'a+');
			if($f){
				fwrite($f,"GET_UPDATE_PUT_ROOM_SUCCESS: RoomID: ".$room_id." Price: ".$price." Start-time: ".$timeStart." End-time: ".$timeEnd." Date-debug:".gmdate('Y-m-d H:i:s')."\r");
			}
			fclose($f);		        	
	        
	        return "情報を保存しました。";
		}catch(Exception $e){
	    	$file='../../../log/error/'.date("Y-m-d").'.txt';
			$f=fopen($file,'a+');
			if($f){
				fwrite($f,"GET_UPDATE_PUT_ROOM_ERROR: RoomID: ".$room_id." Error: ".$e->getMessage()." Date-debug:".gmdate('Y-m-d H:i:s')."\r");
			}
			fclose($f);
			return "予想できないエラーは起こったので、もう一度お願いします。"; 
	    }         
	}
	
    
	/**
     * @author Hienbv
	 * @description あるユーザの存在するかどうかチェックするためメソッド
     * @param unknown_type $user_id
	 * @return true またfalse
     */
	function check_exited_user_id($user_id){
		$mysqli = $this->connect->getMysqli ();
		$db_name = $this->connect->getDB_name ();
		$sql = "SELECT count(*) FROM $db_name.account where username=?";
		$stmt = $mysqli->prepare($sql);
		$stmt->bind_param("s", $user_id);
		$stmt->execute();
		$stmt->store_result(); 
	 	$rows = $stmt->num_rows;
		$col1 = 0;
	 	if($rows != 0){
	 		$stmt->bind_result($col1);
	 		$stmt->fetch();
	 	}
		$stmt->close();
		if($col1 == 0) return false;
		return true;
	}
	
    
	/**
     * @author Hienbv
	 * @description 予約のタイミングを確認するためメソッド
     * @param unknown_type $id not null
	 * @param unknown_type $room_id not null
     * @param unknown_type $date
     * @param unknown_type $timeStart 
     * @param unknown_type $timeEnd 
     * @return　true またfalse
     */
	function check_date_put_room($id, $id_room, $date, $timeStart, $timeEnd){
		$mysqli = $this->connect->getMysqli ();
		$db_name = $this->connect->getDB_name ();
		$sql = "SELECT * FROM $db_name.order where room_id=$id_room and start_time like '%$date%'";
		if($id != ''){
			$sql = "SELECT * FROM $db_name.order where id!=$id and room_id=$id_room and start_time like '%$date%'";
		}
		
		$result = $mysqli->query($sql);
        $i=0;
        $start = null;
        $end = null;
        $_timeStart = $this->convertTimeToNumber($timeStart);
        $_timeEnd = $this->convertTimeToNumber($timeEnd);
        $rs=NULL;
	 	while($row = $result->fetch_array(MYSQLI_ASSOC)) {
	 		$start = $this->convertTimeToNumber(substr($row['start_time'], 11));
	 		$end = $this->convertTimeToNumber(substr($row['end_time'], 11));
	 		if(($_timeStart>$start && $_timeStart<$end) || ($_timeEnd>$start && $_timeEnd<$end)){
	 			return true;
	 		}else if($_timeStart==$start && $_timeEnd==$end){
	 			return true;
	 		}else if($_timeStart<$start && $_timeEnd>$end){
	 			return true;
	 		}
	 	}	 	
	 	return false;
	}
    
    
	/**
     * @author Hienbv
	 * @description タイミングを数字に変化するためメソッド
     * @param unknown_type $time
     * @return 数字
	 */
	function convertTimeToNumber($time){
		$hh = substr($time, 0,2);
		$mm = substr($time, 3,2);
		$number = 0;
		if($mm == '30'){
			$number = $hh + 0.5;			
		}else{
			$number = $hh + 0;
		}
		return $number;
	}
    
    
	/**
     * @author Hienbv
	 * @global danh sach dat phong ve do thi timeline
	 * Enter description here ...
	 * @description タイミングをJsonで出すためメソッド
     * @param unknown_type $room_id
	 * @param unknown_type $date
     * @return　
	 */
function getTimelineJson($room_id, $date){		
		try{
			//
			$mysqli = $this->connect->getMysqli ();
			$db_name = $this->connect->getDB_name ();
			$sql = "SELECT * FROM $db_name.order where room_id=$room_id and status IN (2,1) and start_time like  ";		
			$count = -3;
			$room = null;	$color = null;	$max = 0;
			//
			$jsonDate = '';
			for($i=0;$i<7;$i++){
				if($jsonDate == ''){
					$jsonDate = substr($this->getDate($date, $count),0, 5);
				}else {
					if($count==0){
						$jsonDate = $jsonDate.',<label style="color:red;">'.substr($this->getDate($date, $count),0, 5).'</label>';
					}else{
						$jsonDate = $jsonDate.','.substr($this->getDate($date, $count),0, 5);
					}
					
				}
				
				$_sql = $sql."'%".$this->getDate($date, $count)."%'";
				$result = $mysqli->query($_sql);
				$start = '';	$end = '';			
				$tmp = null;	$tmp[0] = 0;			
				$j=0;			$color[$i] = 0;
				while($row = $result->fetch_array(MYSQLI_ASSOC)) {				
					$start = $this->convertTimeToNumber(substr($row['start_time'], 11));				
		 			$end = $this->convertTimeToNumber(substr($row['end_time'], 11));
		 			if($start == 0) $color[$i] = 1;
		 			$tmp[$j+1] = $start;
		 			$tmp[$j+2] = $end;
		 			$j = $j + 2;		
				}
				if($j>$max) $max = $j;
				sort($tmp,SORT_NUMERIC);
				foreach ($tmp as $key => $val) {
					$room[$i][$key] = $val;
				}			
				$count++;
			}
			for($i=0;$i<7;$i++){
				for($x=count($room[$i]);$x<=$max;$x++){
					$room[$i][$x] = 0;
				}
				$next = 0;
				for($h=0;$h<=$max+1;$h++){		
					if($h == $max+1){
						$room[$i][$h] = 24-$next;
					}else{				
						$tmp = 	$room[$i][$h];
						$room[$i][$h] = $room[$i][$h]-$next;	
						$next = $tmp;
					}			
				}
			}
			//
			$jsonTime = null;
			for($z=0;$z<=$max+1;$z++){
				$jsonTime[$z] = '';
				for($i=0;$i<7;$i++){
					if($jsonTime[$z] == ''){
						$jsonTime[$z][$i] =$room[$i][$z];
					}else{
						$jsonTime[$z][$i] =$room[$i][$z];
					}				
				}
			}
			$j = 0;
			for($i=(count($jsonTime)-1);$i>=0;$i--){
				if($j%2==0){
					$rsxx[$j]['name']='空';
				}else{
					$rsxx[$j]['name']='予約済み';
				}	
				//$rsxx[$j]['name']='1';
				//echo $rsxx[$j]['name'];
				$rsxx[$j]['data']=$jsonTime[$i];
				$j++;
			}
			$str=json_encode($rsxx);
			//
			$json = $jsonDate.'(*)'.$str;
			/*Debug loi*/
			$file='../../../log/debug/'.date("Y-m-d").'.txt';
			$f=fopen($file,'a+');
			if($f){
				fwrite($f,"GET_TIMELINE_SUCCESS: RoomID: ".$room_id." Timeline-date: ".$date." Date-debug:".gmdate('Y-m-d H:i:s')."\r");
			}
			fclose($f);
			return $json;
		}catch(Exception $e){
	    	$file='../../../log/error/'.date("Y-m-d").'.txt';
			$f=fopen($file,'a+');
			if($f){
				fwrite($f,"GET_TIMELINE_ERROR: RoomID: ".$room_id." Error: ".$e->getMessage()." Date-debug:".gmdate('Y-m-d H:i:s')."\r");
			}
			fclose($f);
	    }
	}
	//
	function getDate($date, $number){
		$day = substr($date, 0,2)+$number;
		$month = substr($date, 3,2)+0;
		$year = substr($date, 6,4)+0;
		$tomorrow  = mktime(0, 0, 0, $month , $day, $year);
		$today = getdate($tomorrow);
		if($today['mday']>0 && $today['mday']<10){
			$today['mday'] = "0".$today['mday'];
		}
		if($today['mon']>0 && $today['mon']<10){
			$today['mon'] = "0".$today['mon'];
		}
		return $today['mday']."/".$today['mon']."/".$today['year'];
	}
	
    
	/**
     * @author Hienbv
	 * @description thong tin dat phong
	 * Enter description here ...
     * @param unknown_type $id not null
	 * @param unknown_type $date
     * @param unknown_type $type
     * @param unknown_type $page 
     * @param unknown_type $per_page 
     * @return
	 */
	function get_booking_room($id,$id_room,$date,$type,$page,$per_page){
			$mysqli = $this->connect->getMysqli ();
			$db_name = $this->connect->getDB_name ();
			$sql = "SELECT * FROM $db_name.order where room_id=$id_room and start_time like '%$date%'";
			$result = $mysqli->query($sql);
			if($type==1){
	            $sql=$sql.' limit '.($page*$per_page-$per_page).','.$per_page;
	            //echo $sql;
	            $result = $mysqli->query($sql);
	            $i=0;
	            $rs=''; 
	    	 	while($row = $result->fetch_array(MYSQLI_ASSOC)){
	                 $rs[$i][0]= $row['id'];
	                 $rs[$i][1]= $row['user_id'];
	                 $rs[$i][2]= $row['room_id'];
	                 $rs[$i][3]= $row['start_time'];
	                 $rs[$i][4]= $row['end_time'];
	            	 $rs[$i][5]= $row['total'];
					 $rs[$i][6]= $row['status'];
					 $rs[$i][7]= $row['created_date'];
	                 $i=$i+1;
	    	 	}
	            $result->close();
	    	 	return $rs;
	       }else if($type==2){
	            $totalPage=0;
				//echo $sql;
	            if ($stmt = $mysqli->prepare($sql)) {
	                $stmt->execute();
	            /* bind variables to prepared statement */
	                $stmt->bind_result($totalPage);
	            /* fetch values */
	            while ($stmt->fetch()) {
	            }
	            /* close statement */
	            $stmt->close();
	            }
	           // echo $totalPage;
	            return $totalPage;
	       } 
	
	}
    
    
	/**
     * Created_by : Hienbv
	 * Lay danh sach tat ca cac phong
	 */
	function get_list_room_all(){
		$mysqli = $this->connect->getMysqli ();
		$db_name = $this->connect->getDB_name ();
		$sql = "SELECT room_id,room_name FROM $db_name.room ORDER BY room_name";
		$result = $mysqli->query($sql);
        $i=0;
        $rs=''; 
    	while($row = $result->fetch_array(MYSQLI_ASSOC)){
             $rs[$i]['id'] = $row['room_id'];    
             $rs[$i]['name'] = $row['room_name'];
             $i++;
    	}
        $result->close();
    	return $rs;
	}
	
    
	/**
     * Created_by : Hienbv
	 * 
	 * Enter description here ...
     * @param unknown_type $id not null
	 * @param unknown_type $uname not null
     * @param unknown_type $page
     * @param unknown_type $per_page 
     * @param unknown_type $type  
	 */
	
	function get_list_user_room($room_id, $uname, $date, $page, $per_page, $type){  
		try{  	
	    	$mysqli = $this->connect->getMysqli();
			$db_name = $this->connect->getDB_name();
			if($type==1){
				$sql = "SELECT o.*, a.username, a.first_name, a.last_name, r.room_name FROM $db_name.room r, $db_name.order o, $db_name.account a ";
			}else if($type==2){
				$sql= "SELECT count(*) FROM $db_name.room r, $db_name.order o, $db_name.account a ";
			}
			
			$oder_by = " ORDER BY o.created_date ";
			$where = " where 1=1 AND o.user_id=a.username AND o.room_id=r.room_id ";
			if($room_id != ''){
				$where = $where." and r.room_id=$room_id";
			}
			if($uname != ''){
				$where = $where.' and upper(a.username) like upper(\'%'.$uname.'%\')';
	            //echo $uname;
	            //echo $where;
			}
			if($date != ''){
				$where = $where.' and upper(o.start_time) like upper(\'%'.$date.'%\')';
	            //echo $uname;
	            //echo $where;
			}
			$sql=$sql.$where.$oder_by;
	        //echo $sql;
			if($type==1){
	            $sql=$sql.' limit '.($page*$per_page-$per_page).','.$per_page;
	            //echo $sql;
	            $result = $mysqli->query($sql); 
	            $i=0;
	            $rs = null; 
	    	 	while($row = $result->fetch_array(MYSQLI_ASSOC)) {    	 			
	                $rs[$i]['id']= $row['id'];                 
	                $rs[$i]['username']= $row['username'];
	                $rs[$i]['name']= $row['first_name'].' '.$row['last_name'];
	                $rs[$i]['room_name']= $row['room_name'];
	                $rs[$i]['start_time']= $row['start_time'];
	                $rs[$i]['end_time']= $row['end_time'];
	            	$rs[$i]['total']= $row['total'] + $row['time_expired']*100000;
		    	 	if($row['status'] == '2'){
		            	$rs[$i]['status']= '終わる';
		            }else if($row['status'] == '1'){
		            	$rs[$i]['status']= '予約する';
		            }else{
		            	$rs[$i]['status']= 'キャンセルする';
		            }            	 
	                $i=$i+1;
	    	 	}
	    	 	//print_r($rs);
	    	 	
	    	 	$file='../../../log/debug/'.date("Y-m-d").'.txt';
				$f=fopen($file,'a+');
				if($f){
					fwrite($f,"GET_LIST_USER_ROOM_SUCCESS: RoomID: ".$room_id." Username: ".$uname." Date-debug:".gmdate('Y-m-d H:i:s')."\r");
				}
				fclose($f);
	            $result->close();
	    	 	return $rs;
	       	}else if($type==2){
	            $totalPage=0;
				//echo $sql;
	            if ($stmt = $mysqli->prepare($sql)) {
	                $stmt->execute();
	            /* bind variables to prepared statement */
	                $stmt->bind_result($totalPage);
	            /* fetch values */
	            while ($stmt->fetch()) {
	            }
	            /* close statement */
	            $stmt->close();
	            }
	           // echo $totalPage;
	           if($totalPage == 0){
	           		$totalPage = 0;
	           }
	            return $totalPage;
	       	} 
		}catch(Exception $e){
	    	$file='../../../log/error/'.date("Y-m-d").'.txt';
			$f=fopen($file,'a+');
			if($f){
				fwrite($f,"GET_LIST_USER_ROOM_ERROR: Error: ".$e->getMessage()." Date-debug:".gmdate('Y-m-d H:i:s')."\r");
			}
			fclose($f);
	    }
	}
	
	
	//phan trang
	function listpage_user_room($room_id, $uname, $date, $page, $per_page){
        $totalrecord = $this->get_list_user_room($room_id, $uname, $date, $page, $per_page, 2);
        if($totalrecord<=$per_page){
            $result[0]=1;
        }
        else{
            for($i=0;$i<($totalrecord/$per_page);$i++){
                $rs[$i]=$i+1;
            }
            //echo count($rs);
            if(count($rs)>5){
                if($page<=4){
                    for($i=0;$i<5;$i++){
                        $result[$i]=$i+1;
                    $result[5]=-2;    
                    }
                }
                else if($page>4 && $page<(count($rs)-3)){
                    //echo 'day nay';
                    $result[0]=-1;
                    $result[6]=-2;
                    for($i=1;$i<6;$i++){
                         $result[$i]=$rs[$page-3+$i];    
                    }
                }
                else {
                    $result[0]=-1;
                    for($i=5;$i>0;$i--){
                        $result[$i]=$rs[(count($rs)+$i-6)];
                    }
                }                
            }
            else{$result=$rs;}
        }
        return $result;
    }    
    
    /**
     * @author Hienbv
	 * @global nang huy dat phong
	 */
    function cancelRoom($id , $status){
    	$phi_huy_phong = 5000;
    	try{
	    	$mysqli = $this->connect->getMysqli();
			$db_name = $this->connect->getDB_name();
	        $sql="UPDATE $db_name.order set status=$status, total=$phi_huy_phong WHERE id=".$id;
	        //echo $sql;
	        $mysqli->query("BEGIN");
	        $rs=$mysqli->query($sql);
			if($rs){
				// Ghi vao file Log
				// Code de day			
	            $mysqli->query("COMMIT");
				$result= 'Hủy thành công!';
			}
			else $result= '予想できないエラーは起こったので、もう一度お願いします。';
	        $mysqli->close();
	        
	        $file='../../../log/debug/'.date("Y-m-d").'.txt';
			$f=fopen($file,'a+');
			if($f){
				fwrite($f,"GET_CANCEL_PUT_ROOM: RoomID: ".$id." Date-debug:".gmdate('Y-m-d H:i:s')."\r");
			}
			fclose($f);
	        return $result; 
    	}catch(Exception $e){
	    	$file='../../../log/error/'.date("Y-m-d").'.txt';
			$f=fopen($file,'a+');
			if($f){
				fwrite($f,"GET_TIMELINE_ERROR: RoomID: ".$id." Error: ".$e->getMessage()." Date-debug:".gmdate('Y-m-d H:i:s')."\r");
			}
			fclose($f);
	    }
    }
    
    
	/**
     * @author Hienbv
	 * @description thong tin nguoi dung dat phong
	 * Enter description here ...
     * @param unknown_type $id
     * @return
	 */
	function get_user_room_id($id){
    	$mysqli = $this->connect->getMysqli();
		$db_name = $this->connect->getDB_name();
        $sql = "SELECT o.*, o.status statusx, a.*, r.room_name, r.chair, r.price, r.description FROM $db_name.room r, $db_name.order o, $db_name.account a ";
        $where = " where 1=1 AND o.user_id=a.username AND o.room_id=r.room_id AND o.id=".$id;
        //echo $sql;
        $sql = $sql.$where;
        $rsxx=$mysqli->query($sql);
        $i = 0;
        $rs = null;
        while ($row = $rsxx->fetch_array(MYSQLI_ASSOC)){
        	$rs[$i]['id']= $row['id'];            
        	     
            $rs[$i]['username']= $row['username'];
            $rs[$i]['name']= $row['first_name'].' '.$row['last_name'];
            $rs[$i]['address']= $row['address'];
            $rs[$i]['mobi']= $row['mobi'];
            $rs[$i]['tell']= $row['tell'];
            $rs[$i]['email']= $row['email'];
                        
            $rs[$i]['room_id']= $row['room_id'];
            $rs[$i]['room_name']= $row['room_name'];
            $rs[$i]['chair']= $row['chair'];
            $rs[$i]['price']= $row['price'];
            $rs[$i]['description']= $row['description'];
            
            $rs[$i]['date']= substr($row['start_time'], 0, 10);
            $rs[$i]['start_time']= substr($row['start_time'], 11, 16);
            $rs[$i]['end_time']= substr($row['end_time'], 11, 16);
            $rs[$i]['status'] = $row['statusx'];
           	$rs[$i]['total']= $row['total'];
           	$rs[$i]['time_expired']= $row['time_expired'];
                       	 
            $i=$i+1;
        }
		return $rs; 
    }
}
?>